$(function(){
	var shareCode = $('#j_share_code').val();
	//openApp("unclone://download/share_list?code="+shareCode);
	function openApp(schemeUrl,beforeCallback,errorCallback){
		if($.isFunction(beforeCallback) && beforeCallback()) {
			return false;
		}

		//清除上次下载记录
		$("#unclone-download").remove();
		var startTime = Date.now();
		var ifr = document.createElement('iframe');
		ifr.src = schemeUrl;
		ifr.style.display = 'none';
		ifr.id = 'unclone-download';
		document.body.appendChild(ifr);
		var t = setTimeout(function() {
			var endTime = Date.now();

			if (!startTime || endTime - startTime < 3000 + 200) {
				console.log("without");
				if($.isFunction(errorCallback) && errorCallback()) {
					return false;
				}
			} else {
			}
		}, 1000);

		window.onblur = function() {
			clearTimeout(t);
		}
	}

	//$("#qrcode_img").attr("src","http://qr.liantu.com/api.php?text="+encodeURIComponent(location.href));
	$(".qrcode-img-box").qrcode({
		render	: (!!window.ActiveXObject&&!!document.documentMode)?"table":"canvas",
		text	: location.href,
		size:225
	});
	$("#qrcode-box").click(function(){
		$("#qrcode-box").fadeOut("fast");
	});
	$("#qrcode").click(function(){
		$("#qrcode-box").fadeIn("fast");

	});
	$(".qrcode-img-box").click(function(){
		return false;
	});
	var site_tip = new $.site_tip();
	$.ajaxSetup ({
		cache: false, //关闭AJAX相应的缓存
		error: function(e){
			if((e.status>=400 && e.status<=599))
			{
				//tip.isAnimal=true;
				site_tip.setContent("服务器请求超时，请稍后重试!",true,false);
				site_tip.show();
				$("body").trigger("networkError");
			}
			//console.log(Site_tip);
			// alert("网络连接失败！");
			/*Site_tip.setContent("网络连接失败!");
			 Site_tip.show();*/

		},
		complete:function()
		{
			$("body").trigger("ajaxComplete");
		}
	});
	var breadcrumbsInit  = $('#j_breadcrumbs').html();
	(function(){
        //取得带#的URL
		var hashStr = location.hash;
        //置换为空
		hashStr = hashStr.replace('#', '');
        //如果存在则是二级目录,否则为首级
		if(hashStr){
			restore(hashStr);
		} else {
            //初始化
			init();
		}
	})();
	/*mobShare.config( {

		debug: false, // 开启调试，将在浏览器的控制台输出调试信息

		appkey: 'c6dd59c38b2a'
	});*/
	$("body").delegate(".row-btn-download","click",function(){
		var me=$(this);
		var id = me.data("id");
		var code = $('#j_share_code').val();
		var type = me.data("type");
		var isQrcode = me.data("qrcode");
		me.attr("disabled",true).addClass("loading");
		var text = me.text();
		$.ajax({
			url:"/share_page/get_download_link",
			dataType:"json",
			data:{code:code,id:id,type:type},
			success:function(ret)
			{
				if(ret.success && ret.url)
				{
					//location.href = ret.url;
					if(isQrcode){
						/*mobShare.config( {
							params: {
								url: location.origin+ret.url
							}
						});
						//console.log(location.origin+ret.url);
						var sdk = mobShare("weixin");
						sdk.send();*/
					}else{
						/*
						fileUrl = "unclone://download/share_list?code=" + shareCode + "&id=" + id;
						openApp(fileUrl, false, function(){
							download(ret.url);
						}, true);*/
						download(ret.url);
					}
				}
				else
				{
					site_tip.setContent(ret.message);
				}
			},
			complete:function()
			{
				me.attr("disabled",false).html(text).removeClass("loading");
			}
		});
		return false;
	});

	/*
	//已使用hover来显示
	function tipover() {
		var fmt = $("#fm-tip");
		if (fmt.is(":hidden")) {
			fmt.show();
		}
	}
	function tipleave() {
		var fmt = $("#fm-tip");
		if (fmt.is(":visible")) {
			fmt.hide();
		}
	}
	.hover(function(),function())
	$("#j-fmtip-over").mouseover(function(){
		tipover();
	})
	$("#fm-tip").mouseover(function(){
		tipover();
	})
	$("#j-fmtip-over").mouseleave(function() {
		tipleave();
	})
	$("#fm-tip").mouseleave(function() {
		tipleave();
	})
	*/

		function download(href)
	{
		//window.open(href);
		location.href=href;
		//document.getElementById("download_iframe").src=href;
		//window.download_iframe.location.href = href;
		//console.log(window.download_iframe.location);
		//$("#download_iframe").attr("src",href);
		/*location.href = href;
		return;*/
		/*var form = document.createElement("form");
		$(form).css({visibility:'hidden'}).attr({target:"download_iframe",action:href,method:"get"}).append("<input type='hidden' name='t' value='"+new Date().getTime()+"'/><input type='submit' class='submit-btn' style='display: none;' value='提交'/>");
		$("body").append(form);
		$(form).find(".submit-btn").click();*/
	}
	function parseHtml(html)
	{
		return html.replace(/\\u003C/gi,"<").replace(/\\u003E/gi,">");
	}

	var loadProcess;
	function restore(hashStr){
		var hash = hashStr.split('&');
		var fid = hash[0];
		var code = $('#j_share_code').val();
		var url = '/share_page/get_data';
		$('#j_share_data').html('<div class="list-loading-box">正在加载...</div>');
		$.getJSON(url, {code: code, fid: fid}, function(data){
			if(data.success){
				$('#j_share_data').html(parseHtml(data.share_data));
				$('#j_breadcrumbs').html(parseHtml(data.share_path));
				$('#j_share_flag').text(hash[1]).attr('title', hash[1]);
				is_share_type(hash[2]);
			}
			else
			{
				var html = '<div class="error-box error-2">'+data.message+'</div>';
				/*if(data.ret == -2){
				 html = '<div class="error-box error-2">'+data.message+'</div>';
				 } else {
				 html = '<div class="error-box">'+data.message+'</div>';
				 }*/
				$('#down-main').find('.main').remove();
				$('#down-main').append(html);
			}
		});
	}

    //首次加载code的初始化数据
	function init(){
		if($("#no-file").length>0)
		{
			return true;
		}
		if(loadProcess)
		{
			loadProcess.abort();
		}
		var code = $('#j_share_code').val();
		var url = '/share_page/get_share';
		$('#j_share_data').html('<div class="list-loading-box">正在加载...</div>');
		loadProcess = $.getJSON(url, {code: code}, function(data){
			if(data.success){
				$('#j_share_data').html(parseHtml(data.share_data));
				$('#j_share_flag').text(data.share_name).attr('title', data.share_name);
				$('#j_share_type').val(data.share_type);
				is_share_type(data.share_type);
				if(data.share_type == 1){
					$('.icon-checkbox').addClass('icon-checkbox-active');
					$('#j_share_data').data('sel_count', 1);
					$('.j_checkbox').each(function(){
						this.checked = true;
					});
					$('#j_sel_all').data('active', 1);
					//$('#j_down_title').find('.col-2').html('全选');
				}
				return true;
			} else {
				var html = '<div class="error-box error-2">'+data.message+'</div>';
				/*if(data.ret == -2){
					html = '<div class="error-box error-2">'+data.message+'</div>';
				} else {
					html = '<div class="error-box">'+data.message+'</div>';
				}*/
				$('#down-main').find('.main').remove();
				$('#down-main').append(html);
			}
		});
	}

    //文件类型(左上角文件类型图标)
	function is_share_type(type){
		var $list = $('#j_share_data').find('.list');
		if(!type){
			return;
		}
		var icon = '';
		if(type == 3){
			//分享的是目录
			icon = 'more';
		}
		else if(type == 2){
			//分享的是文件夹
			icon = 'dir';
		} else {
			//分享的是文件
			icon = $list.data('icon');
		}
		icon = 'pro-' + icon;
		$('#j_share_icon').addClass(icon);
	}
	
	//点击进入目录
	$('#j_share_data').on('click', '.j_folder', function(){
		ajaxData(this);
	});
	
	$('#j_breadcrumbs').on('click', '.j_path_item', function(){
		ajaxData(this);
	});

    //触发事件
	function ajaxData(that){
		var fid = $(that).data('fid');
		var code = $('#j_share_code').val();
		
		sel_count = 0;
		$('#j_share_data').data('sel_count', sel_count);
		$('#j_down_title').find('.desc').html($('#j_initDesc').html());
		$('#j_sel_all').removeClass('icon-checkbox-active').data('active', 0);

        //进入首层
		if(fid == '/'){
			init();
			location.hash = '';
			$('#j_breadcrumbs').html(breadcrumbsInit);
			return;
		}

		var url = '/share_page/get_data';
		$('#j_share_data').html('<div class="list-loading-box">正在加载...</div>');
		$.getJSON(url, {code: code, fid: fid}, function(data){
			if(data.success){
				$('#j_share_data').html(parseHtml(data.share_data));
				$('#j_breadcrumbs').html(parseHtml(data.share_path));
				var share_flag = $('#j_share_flag').text();
				var share_type = $('#j_share_type').val();
				location.hash = fid+'&'+share_flag+'&'+share_type;
			}
		});
	}
	
	(function(){
		var sel_count = $('#j_share_data').data('sel_count');
		if(sel_count == undefined || sel_count == null){
			sel_count = 0;
			$('#j_share_data').data('sel_count', sel_count);
			var initDesc = $('#j_down_title').find('.desc').html();
			$('body').append('<div id="j_initDesc" style="display:none;">'+initDesc+'</div>');
		}
	})();
	
	/*全选*/
	$('#j_sel_all').on('click', function(){
		var $this = $(this);
		var active = $this.data('active');
		var flag = true;
		if(active == 1){
			$('.icon-checkbox').removeClass('icon-checkbox-active');
			$this.data('active', 0);
			flag = false;
		} else {
			$('.icon-checkbox').addClass('icon-checkbox-active');
			$this.data('active', 1);
		}
		$('.j_checkbox').each(function(){
			this.checked = flag;
		});
		var f_count = $('#j_f_count').val();
		if(flag){
			if($('#j_share_type').val()==1){
				var html = $('#j_initDesc').html();
				html = html.replace('文件', '全选');
			} else {
				var html = '已选中'+f_count+'个文件/文件夹';
			}
			sel_count = f_count;
		} else {
			var html = $('#j_initDesc').html();
			sel_count = 0;
		}
		$('#j_share_data').data('sel_count', sel_count);
		$('#j_down_title').find('.desc').html(html);
	});
	
	/*单选*/
	$('#j_share_data').on('click', '.j_icon_checkbox', function(){
		var $this = $(this);
		var prev = $this.prev().get(0);
		var sel_count = $('#j_share_data').data('sel_count');
		
		if(prev.checked){
			prev.checked = false;
			$this.removeClass('icon-checkbox-active');
			sel_count--;
		} else {
			prev.checked = true;
			$this.addClass('icon-checkbox-active');
			sel_count++;
		}
		var flag = true;
		$('.j_checkbox').each(function(){
			if(!this.checked){
				flag = false;
				return;
			}
		});
		if(flag){
			$('#j_sel_all').addClass('icon-checkbox-active').data('active', 1);
		} else {
			$('#j_sel_all').removeClass('icon-checkbox-active').data('active', 0);
		}
		
		if(sel_count == 0){
			var html = $('#j_initDesc').html();
		} else {
			if($('#j_share_type').val()==1){
				var html = $('#j_initDesc').html();
				html = html.replace('文件', '全选');
			} else {
				var html = '已选中'+sel_count+'个文件/文件夹';
			}
		}
		$('#j_share_data').data('sel_count', sel_count);
		$('#j_down_title').find('.desc').html(html);
	});
	
	//下载文件,触发打包
	$('#j_down_btn').on('click', function(){
		var that = this;
		$(that).attr("disabled",true).text("下载中...");
		var isChecked = false;
		var f_fid_arr = [];

        var f_folders = []; //文件夹id
        var f_files = []; //文件id

        //选择的全部文件/文件夹的总和
		var selCount = $('.j_checkbox:checked').size();
		var count = 0;

		var f_size = 0;
		var size = 0;
        /* //下载一次就出错
		if ($(that).data('down') == 1){
			return;
		}*/
		$('.j_checkbox').each(function(){
			if (this.checked) {
				var $list = $(this).parents('.list');
				var type = $list.data('type');  //文件类型
				var fid = $list.find('.fname').data('fid');
				var code = $('#j_share_code').val();
				isChecked = true;
				count++;
				$(that).data('down', 1);
                //文件夹
				if (type == 2) {
                    f_folders.push(fid);
                //文件
				} else {
                    f_files.push(fid);
				}

                //完成
                if (selCount == count) {
                    var datas = {'folders' : f_folders, 'files' : f_files};
                    //封装文件/文件夹结构
					loadingTips("正在获取下载地址");
                    $.post("/share_page/create_struct",{code:code, data:datas}, function(res){
						loadingTips("",true);
                        if(res.ret == 1){
                            errorTips(res.error);
                            return true;
                        }

                    });
                }
			}
		});

        //没有选择
		if(!isChecked){
			errorTips('请先选择文件');
			return false;
		}
	});
	
	/*响应下载*/
	function trigger_click(rid, fid){
		//var url = "/file_s/d?rid=" + rid;
		var code = $('#j_share_code').val();
		//$('#j_trigger_click').attr('href', url).find('span').trigger('click');
		$.post("/down_home/update",{uuid: code, f_uuid: fid}, function(jsonData){
			
		});
		//记录下载轨迹
		$.post('/api/policies/save_trace', {event : 5, uuid : f_uuid});
	}
	
	function downloadServer(rid_arr, f_uuid_arr, f_size){
		var uuid = $('#j_share_code').val();
		var fCount = rid_arr.length;
		var rid_str = rid_arr.join();
		var f_uuid_str = f_uuid_arr.join();
		$.post("/down_home/update",{uuid: uuid, f_uuid_arr: f_uuid_str}, function(){
			$('#j_down_btn').data('down', 0);
			if(fCount == 1){
				window.location.href="/file_s/d?rid=" + rid_arr[0];
			} else {
				//多个文件需要压缩下载
				if(f_size > 50){
					//总大小大于100M提示用户
					errorTips('所选择的文件大于50M，请分批下载', 230);
					return;
				}
				window.location.href="/down_home/down_file?rid_arr=" + rid_str;
			}
		});
	}

    //错误提示信息
	function errorTips(msg, w){
		/*w = arguments[1] || 162;
		try{
			clearTimeout(time);
		}catch(e){}
		$('#header-error-box').html(msg).width(w).show();
		time = setTimeout(function(){
			$('#header-error-box').html('').hide();
			clearTimeout(time);
		}, 5000);*/
		$("#j_down_btn").attr("disabled",false).text("下载");
		site_tip.setContent(msg);
	}
	function loadingTips(msg,hide)
	{
		if(hide)
		{
			$("#j_down_btn").attr("disabled",false).text("下载");
		}
		site_tip.loadingMsg(msg,hide);
	}
	
});